var app = angular.module("editApp", []),
	userName = UI.getParameterByName('userName'),
//	msgRight = UI.getParameterByName('msgRight'),
	userId = UI.getParameterByName('userId'),
	userids = parseInt($('#headUserId').val()),
	ifm_id = UI.getParameterByName('ifm_id'),
	groupId	= UI.getParameterByName("groupId"),
	groupName	= UI.getParameterByName("groupName");
window.ifmIds = ifm_id;
//msgRight = decodeURI(msgRight);
var timeout_json = function(data, $window) {
	if(data.returnCode == 999994) {
		var ss = 3;
		layer.msg(data.returnMessage + "！<strong class='Ajax_Out'>" + ss + "</strong> 秒后前往登录页", 50, -1);
		var picInt = setInterval(function() {
			if(ss >= 1) {
				ss = ss - 1;
				$('.Ajax_Out').text(ss);
			} else {
				clearInterval(picInt);
				try {
					$window.parent.location.href = data.returnData;
					$window.location.href = data.returnData;
				} catch(e) {
					log('timeout!')
				}
			}
		}, 1000);
		return false;
	}
}

app.config(function($httpProvider) {
	$httpProvider.defaults.headers.put['Content-Type'] = 'application/x-www-form-urlencoded';
	$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
	// Override $http service's default transformRequest
	$httpProvider.defaults.transformRequest = [function(data) {
		/**
		 * The workhorse; converts an object to x-www-form-urlencoded serialization.
		 * @param {Object} obj
		 * @return {String}
		 */
		var param = function(obj) {
			var query = '';
			var name, value, fullSubName, subName, subValue, innerObj, i;

			for(name in obj) {
				value = obj[name];

				if(value instanceof Array) {
					for(i = 0; i < value.length; ++i) {
						subValue = value[i];
						fullSubName = name + '[' + i + ']';
						innerObj = {};
						innerObj[fullSubName] = subValue;
						query += param(innerObj) + '&';
					}
				} else if(value instanceof Object) {
					for(subName in value) {
						subValue = value[subName];
						fullSubName = name + '[' + subName + ']';
						innerObj = {};
						innerObj[fullSubName] = subValue;
						query += param(innerObj) + '&';
					}
				} else if(value !== undefined && value !== null) {
					query += encodeURIComponent(name) + '=' +
						encodeURIComponent(value) + '&';
				}
			}
			return query.length ? query.substr(0, query.length - 1) : query;
		};
		return angular.isObject(data) && String(data) !== '[object File]' ?
			param(data) :
			data;
	}];
});

app.controller('editCtrl', function($scope, $http, $window, $timeout) {
	var vm = $scope.vm = {
		"userAccount":userName,
		"userId":userId,
		"ifm_id":window.ifmIds,
//		"msgRight":msgRight,
		"groupId":groupId,
		"groupName":groupName
	};
	var avoidDup = true;
	$scope.domAjax = function(e) {
//		var data = $scope.content;
		if (window.ifmIds.substr(0,1)==','){window.ifmIds=window.ifmIds.substr(1);}
		$scope.vm.ifm_id = window.ifmIds;
		if (e === 'save') {
			if(avoidDup==false){
				return false;
			}
			var vmm = $scope.vmm = {
				"userType":2,
				"userId":userId,
				"userAccount":userName,
				"ropeProgramme":$scope.vm.ifm_id 
			};
			var updateUrl=basePath+'user/modifyUserPro.do';
			avoidDup = false;
			$.post(updateUrl, vmm).success(function(data) {
				if(data.returnCode==10000){
					layer.msg(data.returnMessage,1,10);
					//保存iframe窗口后，不跳转页面--jquery
					var t = setTimeout(function(){
						window.parent.$(".ktab").find('.pNumBtn a.cur').trigger('click');
						window.parent.layer.closeAll();
					},1000);
					return false;
				}else {
					layer.msg(data.returnMessage, 2, -1);
					avoidDup = true;
					return false;
				}  
			});
		}
	};
});
app.directive('agSelect', function($http) {
	return {
		restrict: 'AE',
		scope: {
			newsEvaluation: '=newsEvaluation',
			newsType: '=newsType'
		},
		template: '<div class="ui_select"><span class="ui_s_t" ng-bind="stxt"></span><div class="ui_s_bk"><a href="javascript:void(0)" ng-repeat="key in datas"  ng-bind="key.dicValue" data-id="{{key.dicValueCode}}"></a></div></div>',
		controller: function($scope, $element, $attrs) {
			var a = $element.find('.ui_s_t'),
				b = $element.find('.ui_s_bk'),
				c = $attrs.ajaxs,
				d = $attrs.loadajaxs;
			$element.children('.ui_select').css({
				'zIndex': 99 - ($scope.$id - 0),
				"margin-left": 0
			});
			$element.bind('click', function() {
				b.slideDown();
			});
			$element.bind('mouseleave', function() {
				if(a.text() != "") {
					b.hide();
				}
			});
		},
		link: function($scope, $element, $attrs) {
			$scope.stxt = '';
			var a = $element.find('.ui_s_t'),
				b = $element.find('.ui_s_bk'),
				c = $attrs.ajaxs;

			if(c != undefined) {
				$http.get(c).success(function(data) {
					$scope.datas = data.returnData;
				});
			}

			b.find('a').live("click", function() {
				b.hide();
				$(this).addClass('cur').siblings().removeClass('cur');
				a.text($(this).text());
				$scope.stxt = $(this).text();
				if($attrs.theme != undefined) {
					$scope.theme = $(this).attr('data-id');
				}
				$scope.$apply();
				return false;
			});
		}
	}
});

$(function() {
	laydate.skin('molv');
	$('.ui_select').each(function() {
		var _ = $(this),
			_a = _.find('.ui_s_t'),
			_c = _.find('.ui_s_bk'),
			_ca = _c.find('a');
		_a.live('click', function() {
			_c.slideToggle(200, "easeInSine");
		});
		_ca.live('click', function() {
			$(this).addClass('cur').siblings().removeClass('cur');
			_a.text($(this).text());
			_c.slideToggle(200, "easeInSine");
		});
		_c.live('mouseleave', function() {
			_c.stop(false, true).slideUp(200, "easeInSine");
		});
	});

	$('.ui_select').live('keyup', function(e) {
		var _ = $(this),
			b = _.find('.ui_s_bk'),
			di = 27;
		_.focus();
		e = e || window.event;
		var indx = b.find('a.cur').index() || 0;
		if(e.keyCode == 40) {
			var aindx = indx + 1,
				sct;
			if(rindx >= b.find('a').length) {
				rindx = b.find('a').length;
			}
			b.find('a').eq(aindx).addClass('cur').siblings('a').removeClass('cur');
			sct = aindx * di > 180 ? aindx * di - 80 : 0;
			b.scrollTop(sct);
		} else if(e.keyCode == 38) {
			var rindx = indx - 1,
				sct;
			sct = aindx * di > 100 ? aindx * di : 0;
			if(rindx <= 0) {
				rindx = 0;
			}
			b.find('a').eq(rindx).addClass('cur').siblings('a').removeClass('cur');
			sct = rindx * di > 180 ? rindx * di - 80 : 0;
			b.scrollTop(sct);
		} else if(e.keyCode == 13) {
			b.find('a.cur').trigger('click');
			_.blur();
			_.find('.ui_s_t').blur();
		}
		return false;
	});
	
	//open edit Layer
	var editExaDataLayer = null;
	$('.editExaDataBtn').live('click', function() {
		var editExaDataLayer = $.layer({
			type: 1,
			title: false,
			offset:['0px',''],//控制坐标的位置
			area: ['900', 'auto'],
			border: [0], //去掉默认边框
			shade: [0.3, '#000'], //去掉遮罩
			closeBtn: [0, false], //去掉默认关闭按钮
			fadeIn: 500,
			move: "#editExaData_tile",
			page: {
				dom: '#editExaDataLayer'
			}
		});
		//自设关闭
		$('#editExaDataLayer > .closeBtn,#editExaDataLayer .cancelLayer').live('click', function() {
			layer.close(editExaDataLayer);
		});
	});

	var getSs=function(v){
		if(window.ifmIds&&window.ifmIds!=""){
			var cls=window.ifmIds.split(',');
			for(ii=0;ii<cls.length;ii++){
				if(v==cls[ii]){
					return false || ii;
				}
			}
		}
	}

	var edit = {
//		"queryCheck": function(ids, names) {
//	        var $selectShowSpan = $(".editExaDataBtn");
//	        var $showSpan = $selectShowSpan.parent().prev("span");
//	        $selectShowSpan.attr({
//	            ifm_id: ids
//	        });
//	        $showSpan.attr({
//	            ifm_id: ids
//	        });
//	        $showSpan.text(names);
//	    },
		"qTagList": function(_this, ifmIdArr, jsons, pIndex, pageSize) {
			//单页显示总条数为‘全部’时，默认为10000000
			if(isNaN(pageSize)){
				pageSize=10000000;
			}
			var groupId = $("#moreSelect").attr("group_id");
			var _obj = $("#CustomsAreaList");
			$.ajax({
				type: "POST",
				url: basePath + "group/selectGroupScheme.do?pageIndex="+pIndex+"&pageSize="+pageSize+"&gId="+groupId,
				data: jsons,
				success: function(data) {
					if(data.returnCode == 10000) {
						var s2 = data.returnData.length;
						var strHead = "<div class='selects w60'>复选框</div><div class='ifmNames w150'>方案名称</div><div class='ifmNotes w536'>方案备注</div>";
						var strPage = "<div class='pages' style='position:relative;'><div class='ui_page' id='pageArea'></div></div>";
						if(s2 > 0) {
							var htmls = "";
							for(var i = 0; i < s2; i++) {
								var checkedBtn = "";
								var checked = "";
								var ifm_id2 = data.returnData[i].ifmId;
								var checkeddefault = "";
								var num = ifmIdArr.length;
								var tf = null;
								for(var nn = 0; nn < num; nn++) {
										if(getSs(ifm_id2)||getSs(ifm_id2)==0) {
										checkedBtn = "true";
										checked = "checked";
										break;
									} else {
										checkedBtn = "false";
										checked = "";
									}
								}
								htmls += '<tr class="td infoLlist"><td class="tc w60"><span class="ui_checkbox '  + checked + '" ifm_id= ' + data.returnData[i].ifmId + ' checkedBtn=' + checkedBtn + ' checkeddefault=' + checkeddefault + '></span></td><td class="tc w150 tName"><font>' + data.returnData[i].ifmName + '</font></td><td class="tc w536"><font title="'+ data.returnData[i].ifmNote +'">' + data.returnData[i].ifmNote + '</font></td>';
							}
							$(".headDiv").html(strHead);
							_obj.html(htmls);
							$(".pageDiv").html(strPage);
							//加入分页
							paging.loadPage(data);
							//判断是否全选
							checkTrueFalse();
						}else if(s2 < 1) {
							$(".headDiv").html(strHead);
							_obj.html("<tr><td class='tc' colspan='3'>很遗憾，没有查询到相关的数据！</td></tr>");
						}
					} else if(data.returnCode == 999994) {
						setUserTimeout(data);
					} else {
						layer.msg(data.returnMessage, 2, -1);
					}
				},
				error: function(message) {
					layer.msg("操作失败，请重试！", 2, -1);
				},
				beforeSend: function() {
					var imgGif = "<p class='loadingGif'></p>";
					_obj.html(imgGif);
				}
			});
		}
	}

	$(".infoLlist .ui_checkbox").live("click", function() {
		if($(this).attr("checkedBtn") == "true") {
			$(this).attr("checkedBtn", "false");
			$(this).removeClass("checked");
			if($(this).attr("ifm_id")!=undefined){
				var qc=getSs($(this).attr("ifm_id"));
				if(qc||qc==0){
					var ifmIdsArr=window.ifmIds.split(',');
					ifmIdsArr.splice(qc,1);
					window.ifmIds=ifmIdsArr.join(',');
				}
			}
		} else {
			$(this).attr("checkedBtn", "true");
			$(this).addClass("checked");
			if($(this).attr("ifm_id")!=undefined){
				var qc=getSs($(this).attr("ifm_id"));
				if(!qc){
					if(window.ifmIds!=""){
						window.ifmIds+=(','+$(this).attr("ifm_id"));
					}else{
						window.ifmIds+=$(this).attr("ifm_id");
					}
				}
			}
		}
	});

	$(".editExaDataBtn").live("click", function() {
		var strId = $(this).attr('ifm_id');
		var ifmIdArr = strId.split(",");
		edit.qTagList($(this), ifmIdArr, "", curPage, numList);
	});

	$(".selectAllAreaGoGo .allSel").live("click", function() {
		var checkedbtn = $(this).attr("checkedbtn");
		var len = $("#CustomsAreaList .infoLlist .ui_checkbox").length;
		//判断在点击全选按钮之前，列表中是否存在已勾选的状态
		for(var ii=0;ii<len;ii++){
			if($("#CustomsAreaList .infoLlist .ui_checkbox").eq(ii).attr("checkedbtn")=="true"){
				$("#CustomsAreaList .infoLlist .ui_checkbox").eq(ii).attr("data-select","true");
			}else{
				$("#CustomsAreaList .infoLlist .ui_checkbox").eq(ii).removeAttr("data-select");
			}
		}
		if(checkedbtn == "false") {
			$("#CustomsAreaList .infoLlist .ui_checkbox, .allSel").addClass("checked").attr("checkedbtn", "true");
			for(var i=0;i<len;i++){
				if($("#CustomsAreaList .infoLlist .ui_checkbox").eq(i).attr("data-select")=="true"){
					var	nn="";
				}else{
					var nn= $("#CustomsAreaList .infoLlist .ui_checkbox").eq(i).attr("ifm_id");
				}
				var qc=getSs(nn);
				if(!qc){
					if(window.ifmIds!=""){
						window.ifmIds+=(nn!="" ? (',' + nn) : nn);
					}else{
						window.ifmIds+=nn;
					}
				}
			}
		} else {
			$("#CustomsAreaList .infoLlist .ui_checkbox, .allSel").removeClass("checked").attr("checkedbtn", "false");
			for(var i=0;i<len;i++){
				var nn = "";
				nn = $("#CustomsAreaList .infoLlist .ui_checkbox").eq(i).attr('ifm_id');
				var qc=getSs(nn);
				if(qc||qc==0){
					var ifmIdsArr=window.ifmIds.split(',');
					ifmIdsArr.splice(qc,1);
					window.ifmIds=ifmIdsArr.join(',');
				}
			}
		}
	});

	$("#CustomsAreaList .infoLlist .ui_checkbox").live("click", function() {
		checkTrueFalse();
	});

	function checkTrueFalse() {
		var isTrue = "true";
		$("#CustomsAreaList .infoLlist .ui_checkbox").each(function() {
			var checkedbtn = $(this).attr("checkedbtn");
			if(checkedbtn == "false") {
				isTrue = "false";
				return;
			}
		});
		if(isTrue == "false") {
			$(".selectAllAreaGoGo .allSel").removeClass("checked").attr("checkedbtn", "false");
		} else {
			$(".selectAllAreaGoGo .allSel").addClass("checked").attr("checkedbtn", "true");
		}
	}

	//点击查询
	$("#checkQueryBtn").live("click", function() {
		curPage = 1;
		qDataFun(curPage);
	});
	$('.enterKeyDownElement').keydown(function(e) {
		if(e.keyCode == 13) {
			curPage = 1;
			qDataFun(1);
		}
	});
	//点击触发换页的按钮
	$("#pageArea .pNumBtn a").live("click", function() {
		curPage = parseInt($(this).attr("toPage"));
		qDataFun(curPage);
	});

	//点击触发分批显示的按钮
	$("#pageArea .columnsPage a").live("click", function() {
		numList = parseInt($(this).text());
		curPage = 1;
		qDataFun(curPage);
		subPage = $(this).index();
	});
	//跳转
	$("#pageArea .gopg .btn").live("click", function() {
		curPage = parseInt($("#pageArea .gopg .txt").val());
		//判断输入的页数是否大于最大的页数
		if(curPage>countPage){
			curPage=countPage;
		}
		if(curPage>0){
			qDataFun(curPage);
		}
	});

	function qDataFun(curPages) {
		ifmName = $("#ifmName").val();
		ifmNote = $("#ifmNote").val();
		selectJsonData = null;
		selectJsonData = {
			ifmName: ifmName,
			ifmNote: ifmNote
		};
		var rscArr2 =  $(".editExaDataBtn").attr("ifm_id").split(",");
		edit.qTagList( $(".editExaDataBtn"), rscArr2, selectJsonData, curPages, numList);
	};

	/*
	 * 分页
	 * */
	var numList =10 ;	//每页列数
	var curPage = 1;  //默认第一页
	var subPage=0;  //批量显示添加默认落点
	var totalPage=9; //最多显示分页数
	var selectJsonData = "";
	var countPage = 0;//页数总计
	function jsCk(t){
		if(!/^[1-9][0-9]*$/g.test(t.value)){
			t.value="";
			return false;
		}
	}
	var paging = {
		//加载分页
		"loadPage":function(data){
			var pCount = data.totalPages;//页数
			countPage = pCount;
			var pNums =  data.totalRecords;//总计条数
			var s1 = (totalPage-1)/2;
			var start_page = curPage - s1;
			var end_page = curPage + s1;
			if(start_page<=0){
				end_page = end_page - start_page + 1;
				start_page = 1;
			}
			if(end_page>pCount){
				end_page = pCount;
			}	  		
			var prevHtml ='<a toPage="'+(curPage-1)+'" href="javascript:void(0);"   class="str">&lt;</a>';
			var nextHtml ='<a toPage="'+(curPage+1)+'" href="javascript:void(0);"  class="end" >&gt;</a>';
			if(curPage<2)prevHtml="";
			if(curPage>=pCount)nextHtml="";
			var ppHtml = "";
			for(i=start_page;i<=end_page;i++){
			   var cur = "";
			   if(curPage==i)cur='class="cur"';
			   ppHtml = ppHtml+'<a toPage="'+i+'" href="javascript:void(0);"  '+cur+'>'+i+'</a>';
			}
			var pageHtml = '<span class="ic fl pr20 pCount">共<b>'+pNums+'</b>条记录</span><span class="sw fl pr20 columnsPage">显示 <a href="javascipr:void(0);" class="cur">10</a><a href="javascipr:void(0);" class="cur">50</a><a href="javascipr:void(0);" class="cur">全部</a></span><span class="gopg fr"><span class="fl">跳转到</span><input type="button" class="btn" value="go"><input type="text" min="1" class="txt" onkeyup="jsCk(this)"></span><div class="pg fr pNumBtn">'+prevHtml+ppHtml+nextHtml+'</div>';
			var pageArea = $('#pageArea');
			pageArea.html(pageHtml);
			
  			//每页显示指定的数量
  			var dd = pNums/10;
  			var ddHtmls = "";
  			var pCur = 0;
  			if(pNums>0){
  				pCur=0;
  				pageArea.show();
  			}else if(pNums==0){
  				pCur=4;
  				pageArea.hide();
  			}
  			$("#pageArea .columnsPage").html("显示 <a href='javascript:void(0);'>10</a><a href='javascript:void(0);'>20</a><a href='javascript:void(0);'>50</a><a href='javascript:void(0);'>全部</a>");
  			$("#pageArea .columnsPage a").removeClass("cur").eq(subPage).addClass("cur");
  			var s = 4; 
  			for(var i=0;i<pCur;i++){
  				$("#pageArea .columnsPage a").eq(s).remove();
  				s -=1;
  			}
		}
	}
});
